package com.harmonyos.cases.view;

import com.harmonyos.cases.utils.ProgressFunction;
import com.harmonyos.cases.utils.VersionControlUtil;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.components.JBScrollPane;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

public class DownloadDialog extends DialogWrapper {

    public static final int YES_OPTION = 0;
    /** Return value from class method if NO is chosen. */
    public static final int NO_OPTION = 1;

    private String destDirectory;

    public DownloadDialog() {
        super(true);
        setTitle("插件更新");
        setOKButtonText("下载");
        setCancelButtonText("取消");
        init();
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        JPanel jPanel = new JPanel();
        jPanel.setPreferredSize(new Dimension(360, 150));
        SpringLayout springLayout = new SpringLayout();
        jPanel.setLayout(springLayout);

        JTextArea versionContent = new JTextArea();
        versionContent.setFont(new Font("宋体", Font.PLAIN, 13));
        versionContent.setLineWrap(true);
        versionContent.setWrapStyleWord(true);
        versionContent.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                adjustTextArea(versionContent);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                adjustTextArea(versionContent);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {}

            private void adjustTextArea(JTextArea textArea) {
                int preferredWidth = textArea.getPreferredSize().width;
                int lineWrapWidth = preferredWidth;
                if (textArea.getParent() instanceof JScrollPane) {
                    JScrollPane scrollPane = (JScrollPane) textArea.getParent();
                    preferredWidth = scrollPane.getPreferredSize().width;
                    lineWrapWidth = preferredWidth - scrollPane.getVerticalScrollBar().getWidth();
                }
                textArea.setLineWrap(true);
                textArea.setWrapStyleWord(true);
                textArea.setColumns(lineWrapWidth / textArea.getFontMetrics(textArea.getFont()).charWidth('m'));
            }
        });
        versionContent.setText("更新内容:\n" + VersionControlUtil.getLatestVersionInfo().get("content"));
        versionContent.setEnabled(false);
        JBScrollPane scrollPane = new JBScrollPane(versionContent);
        scrollPane.setPreferredSize(new Dimension(350, 110));
        scrollPane.setVerticalScrollBarPolicy(JBScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        springLayout.putConstraint(SpringLayout.WEST, scrollPane, 5, SpringLayout.WEST, jPanel);
        springLayout.putConstraint(SpringLayout.NORTH, scrollPane, 0, SpringLayout.NORTH, jPanel);
        SwingUtilities.invokeLater(() -> {
            if (scrollPane.getVerticalScrollBar().isVisible()) {
                scrollPane.getVerticalScrollBar().setValue(0);
            }
        });
        jPanel.add(scrollPane);

        JPanel downloadArea = new JPanel();
        downloadArea.setPreferredSize(new Dimension(350, 30));
        downloadArea.setLayout(new BoxLayout(downloadArea, BoxLayout.X_AXIS));
        springLayout.putConstraint(SpringLayout.WEST, downloadArea, 5, SpringLayout.WEST, jPanel);
        springLayout.putConstraint(SpringLayout.NORTH, downloadArea, 10, SpringLayout.SOUTH, scrollPane);
        jPanel.add(downloadArea);

        JTextPane jTextPane = new JTextPane();
        jTextPane.setText("下载目录: ");
        jTextPane.setEnabled(false);
        downloadArea.add(jTextPane);

        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(245, 30));
        textField.setEnabled(false);
        textField.setDisabledTextColor(Color.GRAY);
        springLayout.putConstraint(SpringLayout.WEST, textField, 0, SpringLayout.EAST, jTextPane);
        springLayout.putConstraint(SpringLayout.VERTICAL_CENTER, textField, 0, SpringLayout.VERTICAL_CENTER, jTextPane);
        downloadArea.add(textField);

        JButton jButton = new JButton();
        jButton.setText("···");
        jButton.setPreferredSize(new Dimension(30, 30));
        jButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = fileChooser.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File selectedFolder = fileChooser.getSelectedFile();
                    textField.setText(selectedFolder.getAbsolutePath());
                    destDirectory = selectedFolder.getAbsolutePath();
                }
            }
        });
        springLayout.putConstraint(SpringLayout.WEST, jButton, 5, SpringLayout.EAST, textField);
        springLayout.putConstraint(SpringLayout.VERTICAL_CENTER, jButton, 0, SpringLayout.VERTICAL_CENTER, jTextPane);
        downloadArea.add(jButton);

        return jPanel;
    }

    public static int showDialog() {
        DownloadDialog downloadDialog = new DownloadDialog();
        downloadDialog.show();
        if (downloadDialog.getExitCode() == OK_EXIT_CODE) {
            if(downloadDialog.getDestDirectory()==null||downloadDialog.getDestDirectory().isEmpty()){
                return -1;
            }
            JDialog dialog = new JDialog();
            dialog.setTitle("下载进度");
            dialog.setLocationRelativeTo(null);
            dialog.setSize(270, 70);
            dialog.setModal(true);
            dialog.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    // 中断线程，在线程内部关闭进度条
                    VersionControlUtil.getThread().interrupt();
                }
            });

            JPanel jPanel = new JPanel();
            SpringLayout springLayout = new SpringLayout();
            jPanel.setLayout(springLayout);
            jPanel.setSize(270, 40);
            dialog.add(jPanel);

            JProgressBar progressBar = new JProgressBar(0, 100);
            progressBar.setPreferredSize(new Dimension(185, 4));
            springLayout.putConstraint(SpringLayout.VERTICAL_CENTER, progressBar, 0, SpringLayout.VERTICAL_CENTER, jPanel);
            springLayout.putConstraint(SpringLayout.WEST, progressBar, 20, SpringLayout.WEST, jPanel);
            jPanel.add(progressBar);

            JTextPane jTextPane = new JTextPane();
            jTextPane.setText("0%");
            jTextPane.setEnabled(false);
            springLayout.putConstraint(SpringLayout.VERTICAL_CENTER, jTextPane, 0, SpringLayout.VERTICAL_CENTER, jPanel);
            springLayout.putConstraint(SpringLayout.WEST, jTextPane, 5, SpringLayout.EAST, progressBar);
            jPanel.add(jTextPane);

            VersionControlUtil.downloadLatestVersion(downloadDialog.getDestDirectory(), new ProgressFunction<Integer>() {
                @Override
                public synchronized void apply(Integer progress) {
                    progressBar.setValue(progress);
                    jTextPane.setText(progress + "%");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void stop() {
                    dialog.dispose();
                }
            });
            dialog.setVisible(true);
            return YES_OPTION;
        }
        return NO_OPTION;
    }

    public String getDestDirectory() {
        return destDirectory;
    }

    private class AdaptiveJPanelWithPreferredSize extends JPanel {

        private int height;

        AdaptiveJPanelWithPreferredSize() {
            this.height = 0;
        }

        AdaptiveJPanelWithPreferredSize(int height) {
            this.height = height;
        }

        @Override
        public Dimension getPreferredSize() {
            // 根据内容计算高度
            for (Component comp : getComponents()) {
                Dimension d = comp.getPreferredSize();
                height += d.height;
            }
            return new Dimension(getWidth(), height);
        }
    }
}
